package com.sjax.myapp.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sjax.myapp.domain.User;
import com.sjax.myapp.json.CustomGenericResponse;
import com.sjax.myapp.json.CustomUserResponse;
import com.sjax.myapp.service.UserService;
import com.sjax.myapp.utils.PaginationUtils;

@Controller
@RequestMapping("/crud")
public class UserController {

	private static Logger logger = Logger.getLogger("controller");

	@Resource(name = "userService")
	private UserService userService;

	/**
	 * 获得所有的User 返回页面 下面4个参数是JqGrid自带的参数.
	 * 
	 * @param page
	 *            当前页
	 * @param rows
	 *            总行数
	 * @param sidx
	 *            排序字段
	 * @param sord
	 *            排序方式
	 * @return 返回一个CustomGenericResponse对象
	 */
	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody
	CustomUserResponse getAll(
			@RequestParam("page") String page,
			@RequestParam("rows") String rows,
			@RequestParam("sidx") String sidx,
			@RequestParam("sord") String sord,
			@RequestParam("_search") Boolean isSearch,
			@RequestParam(value = "searchField", required = false) String searchField,
			@RequestParam(value = "searchOper", required = false) String searchOper,
			@RequestParam(value = "searchString", required = false) String searchString,
			@RequestParam(value = "filters", required = false) String filters) {

		long records = 0;
		List<User> users = Collections.emptyList();

		// 如果StringUtils.isNotEmpty(filters)为true,表示多字段查询.
		// filter和jsp页面的multipleSearch: true有关系.表示开启多字段查询.
		// 如果multipleSearch:false 表示单字段查询则filter为null.
		// 可按searchField,searchOper,searchString这3个字段进行查询
		if (StringUtils.isNotEmpty(filters)) {

			users = userService.getUserByParameter(Integer.parseInt(page),
					Integer.parseInt(rows), sidx, sord, filters);

			records = userService.getUserByParameterCount(filters);

		} else {

			// 获得所有的User信息,并根据page和rows进行分页.
			users = userService.getAll(Integer.parseInt(page),
					Integer.parseInt(rows), sidx, sord);

			// User的所有数量
			records = userService.getAllCount();

		}

		// 获得总的页数.
		long total = PaginationUtils
				.getPageCount(records, Long.parseLong(rows));

		CustomUserResponse response = new CustomUserResponse();

		// User信息
		response.setRows(users);

		// 总记录数
		response.setRecords(String.valueOf(records));

		// 当前页数
		response.setPage(page);

		// 总页数
		response.setTotal(String.valueOf(total));

		return response;
	}

	/**
	 * 根据接收的参数进行Edit操作
	 * 
	 * @return 返回一个CustomGenericResponse对象
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public @ResponseBody
	CustomGenericResponse edit(@RequestParam("id") String id,
			@RequestParam("firstName") String firstName,
			@RequestParam("lastName") String lastName) {

		logger.debug("从页面接收到的Edit ID :{" + id + "}");

		User user = new User();
		user.setId(id);
		user.setFirstName(firstName);
		user.setLastName(lastName);

		int success = userService.edit(user);

		CustomGenericResponse response = new CustomGenericResponse();

		if (success == 1) {
			response.setSuccess(true);
			response.setMessage("修改成功!");
		} else {
			response.setSuccess(false);
			response.setMessage(" 修改失败!");
		}
		return response;
	}

	/**
	 * 根据接收的参数进行Add操作
	 * 
	 * @return 返回一个CustomGenericResponse对象
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody
	CustomGenericResponse add(@RequestParam("firstName") String firstName,
			@RequestParam("lastName") String lastName) {

		logger.debug("从页面接收到请求,添加一个NEW User");

		User user = new User();
		user.setFirstName(firstName);
		user.setLastName(lastName);

		int success = userService.add(user);

		CustomGenericResponse response = new CustomGenericResponse();

		if (success == 1) {

			response.setSuccess(true);
			response.setMessage("添加成功!");
		} else {
			response.setSuccess(false);
			response.setMessage("添加失败!");
		}
		return response;
	}

	/**
	 * 根据接收的ID进行Delete操作.
	 * 
	 * @return 返回一个CustomGenericResponse对象
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
	CustomGenericResponse delete(@RequestParam("id") String id) {

		logger.debug("删除ID为{" + id + "}的User");

		User user = new User();

		user.setId(id);

		int success = userService.delete(user);

		CustomGenericResponse response = new CustomGenericResponse();

		if (success == 1) {
			response.setSuccess(true);
			response.setMessage("删除成功!");
		} else {
			response.setSuccess(false);
			response.setMessage("删除失败!");
		}
		return response;
	}

	/**
	 * 批量删除操作
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deleteMore", method = RequestMethod.POST)
	public @ResponseBody
	CustomGenericResponse deleteMore(@RequestParam("id") String[] id) {

		List<User> userList = new ArrayList<User>();

		User user = new User();

		// 把页面接收的id放入一个List里便于操作.
		for (int i = 0; i < id.length; i++) {
			user.setId(id[i]);
			userList.add(user);
		}

		int[] success = userService.deleteMore(userList);

		CustomGenericResponse response = new CustomGenericResponse();

		boolean isSuccess = true;

		// 如果返回为-1,则表示操作失败.
		for (int i = 0; i < success.length; i++) {
			if (success[i] == -1) {
				isSuccess = false;
			}
		}
		if (isSuccess) {
			response.setSuccess(true);
			response.setMessage("批量删除成功!");
		} else {
			response.setSuccess(false);
			response.setMessage("批量删除失败!");
		}
		return response;
	}

}
